﻿#region copyright

// Autofac Quartz integration
// https://github.com/alphacloud/Autofac.Extras.Quartz
// Licensed under MIT license.
// Copyright (c) 2014-2015 Alphacloud.Net

#endregion

#region 导入名称空间

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Autofac;
using Quartz;
using Module = Autofac.Module;

#endregion

namespace LightWork.Autofac.Quartz
{
    /// <summary>
    /// Registers Quartz jobs from specified assemblies.
    /// </summary>
    public class QuartzAutofacJobsModule : Module
    {
        private readonly Assembly[] _assembliesToScan;

        /// <summary>
        /// Initializes a new instance of the <see cref="QuartzAutofacJobsModule" /> class.
        /// </summary>
        /// <param name="assembliesToScan">The assemblies to scan for jobs.</param>
        /// <exception cref="System.ArgumentNullException">assembliesToScan</exception>
        public QuartzAutofacJobsModule(params Assembly[] assembliesToScan)
        {
            if (assembliesToScan == null) throw new ArgumentNullException(nameof(assembliesToScan));
            _assembliesToScan = assembliesToScan;
        }

        public QuartzAutofacJobsModule(List<string> assembliesToScan)
        {
            if (assembliesToScan == null) throw new ArgumentNullException(nameof(assembliesToScan));
            var assemblyList = new List<Assembly>();
            foreach (
                var fullPath in assembliesToScan.Select(asm => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, asm))
            )
            {
                var assembly = Assembly.Load(fullPath);
                assemblyList.Add(assembly);
            }
            _assembliesToScan = assemblyList.ToArray();
        }


        /// <summary>
        /// Override to add registrations to the container.
        /// </summary>
        /// <remarks>
        /// Note that the ContainerBuilder parameter is unique to this module.
        /// </remarks>
        /// <param name="builder">
        /// The builder through which components can be
        /// registered.
        /// </param>
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterAssemblyTypes(_assembliesToScan)
                .Where(type => !type.IsAbstract && typeof(IJob).IsAssignableFrom(type))
                .AsSelf().InstancePerLifetimeScope();
        }
    }
}